const crypto = require("crypto")

const KEY = 'qazwsxedcrfvtgby'
const VI= '123456789qwertyu'

module.exports = {
    /**
     * AES对称加密函数
     * @param {*} data 待加密数据
     * @param {*} key 秘钥
     */
    aesEncrypt:(data,key)=>{
        let keyStr = key || KEY
        const cipher = crypto.createCipheriv('aes-128-cbc', keyStr,VI)
        let crypted = cipher.update(data,'utf8','hex')
        crypted += cipher.final('hex')
        console.log(`[${data}]加密结果：${crypted}`)
        return crypted
    },
    /**
     * AES对称解码函数
     * @param {*} data 待解码字符串
     * @param {*} key 秘钥
     */
    aesDecrypt:(data,key)=>{
        let keyStr = key || KEY
        const crypted = Buffer.from(data,'hex').toString('binary')
        const decipher = crypto.createDecipheriv('aes-128-cbc', keyStr,VI)
        let decrypted = decipher.update(crypted,'binary','utf8')
        decrypted += decipher.final('utf8')
        console.log(`[${data}]解密结果：${decrypted}`)
        return decrypted
    }
}